package su.kozhevnikov.nookbrary;

public class StopWatch {
	private long startTime = 0;
	private long endTime = 0;
	private boolean isRuning = false;
	
	public void start() {
		if (!this.isRuning) {
			this.startTime = System.currentTimeMillis();
			this.isRuning = true;
		}
	}
	
	public void stop() {
		if (this.isRuning) {
			this.endTime = System.currentTimeMillis();
			this.isRuning = false;
		}
	}
	
	public long getElapsedTime() {
		long elapsed = 0;
		if (this.isRuning)
			elapsed = System.currentTimeMillis() - this.startTime;
		else
			elapsed = this.endTime - this.startTime;
		return elapsed;
	}
	
	@Override
	public String toString() {
		long elapsed = this.getElapsedTime();
		long mili = elapsed % 1000;
		elapsed /= 1000;
		long sec = elapsed % 60;
		long min = elapsed / 60 % 60;
		long hour = elapsed / 3600;
		if (hour > 0)
			return String.format("%02d:%02d:%02d.%03d", hour, min, sec, mili);
		else if (min > 0) 
			return String.format("%02d:%02d.%03d", min, sec, mili);
		return String.format("%02d.%03ds", sec, mili);
	}
}
